<script setup lang="ts">
import { ref } from 'vue'
import type { ButtonOnChooseavatar, FormOnSubmit } from '@uni-helper/uni-app-types'
import { getUserInfoByIdService, loginAdminService, loginWeChatService, sendSmsCodeService, smsCodeLoginService } from '@/common/service/users'
import { useUserStore } from '@/common/store'
import hopePopup from '@/common/components/hope-popup.vue'
import { HttpStatusCodes, ResultCode } from '@/common/enum'
import { uploadFile, validatePhoneNumber } from '@/common/utils'

const { contentAreaHeight, tabBarHeight } = useLayoutInfo()
/** 按钮文本 */
const buttonText = ref('发送')
/** 计时器 */
let timer: number

/** 加载状态 */

const { setToken } = useUserStore()

/** 手机验证码登录参数 */
const smsLoginParam = ref({
  phoneNumber: '',
  code: '',
  wxCode: '',
})

/** 验证码倒计时时间 */
const countDownSeconds = ref(60)

/** 是否能获取验证码 */
const canGetCode = ref(true)

/** 开始倒计时 */
const startCountDown = () => {
  canGetCode.value = false
  timer = setInterval(() => {
    if (countDownSeconds.value > 0) {
      countDownSeconds.value--
      buttonText.value = `${countDownSeconds.value}秒`
    }
    else {
      clearInterval(timer)
      countDownSeconds.value = 60
      canGetCode.value = true
      buttonText.value = `重新获取`
    }
  }, 1000)
}

/**
 * 发送验证码
 */
const onSendSms = async () => {
  if (!canGetCode.value)
  // TODO:后续优化 将提示文本转换为常量
    return showSimpleToast('60秒内不能重复获取验证码')

  // 获取手机号码
  const phoneNumber = smsLoginParam.value.phoneNumber.trim()

  // 校验手机号码规则
  if (!validatePhoneNumber(phoneNumber)) {
    return showSimpleToast('手机号码格式不正确')
  }

  // 发送验证码
  const { code, message } = await sendSmsCodeService(Number(phoneNumber))
  if (code === 1) {
    showSimpleToast(message)
  }
  else {
    showSimpleToast('发送成功')
    startCountDown()
  }
}

/**
 * 手机验证码登录
 */

const onSmsLogin = () => {
  const { phoneNumber, code } = smsLoginParam.value

  if (!validatePhoneNumber(phoneNumber)) {
    return showSimpleToast(PHONE_NUMBER_ERROR)
  }

  if (!validateCode(code)) {
    return showSimpleToast(CODE_ERROR)
  }

  uni.login({
    provider: 'weixin',
    success: async (success) => {
      // 获取wxcode
      smsLoginParam.value.wxCode = success.code
      // 短信验证码登录
      const { message, code, data } = await smsCodeLoginService(smsLoginParam.value)
      if (code === ResultCode.FAILURE) {
        return showSimpleToast(message)
      }
      else {
        // 设置token
        setToken(data)
        uni.reLaunch({
          url: PagePath.HOME,
        })
      }
    },
  })
}

/**
 * 一键授权登录参数
 */
const oneClickLoginParams = ref({
  code: '',
  nickname: '',
  avatarUrl: '',
})

/** 弹框组件 ref */
const popupRef = ref<InstanceType<typeof hopePopup> | null>(null)

/**
 * 选择头像
 */
const onChooseAvatar: ButtonOnChooseavatar = (e) => {
  uni.downloadFile({
    url: e.detail.avatarUrl,
    success: async (res) => {
      if (res.statusCode === HttpStatusCodes.OK) {
        const tempFilePath = res.tempFilePath
        // 上传用户头像
        const url = await uploadFile(tempFilePath)
        oneClickLoginParams.value.avatarUrl = url
      }
    },
  })
}

/**
 * 一键登录表单提交
 */
const onOneClickLogin: FormOnSubmit = (e) => {
  const { nickname } = e.target?.value

  // 校验用户昵称
  if (!validateNickname(nickname))
    return showSimpleToast('昵称需要2~6个字符')

  // 获取填充的昵称
  oneClickLoginParams.value.nickname = nickname

  // 登录操作
  uni.login({
    provider: 'weixin',
    success: async (success) => {
      // 获取微信code
      oneClickLoginParams.value.code = success.code
      // 登录微信
      const { data } = await loginWeChatService(oneClickLoginParams.value)
      // 设置token
      setToken(data)
      showSimpleToast(LOGIN_SUCCESS)

      // 跳转首页
      setTimeout(() => {
        uni.reLaunch({
          url: PagePath.HOME,
        })
      }, 1000)
    },
  })
}

/** 登录管理员测试账号 */
const onLoginAdmin = async () => {
  const { data } = await loginAdminService()
  setToken(data)
  showSimpleToast(LOGIN_SUCCESS)
  // 跳转首页
  setTimeout(() => {
    uni.reLaunch({
      url: PagePath.HOME,
    })
  }, 1000)
}
</script>

<template>
  <view class="login">
    <hope-nav-bar :title="PageTitle.LOGIN" is-home-icon />
    <view
      class="login-container" :style="{
        height: `${contentAreaHeight + tabBarHeight}px`,
      }"
    >
      <view class="login-container-content">
        <uni-title title="手机验证码登录" type="h1" />
        <view class="login-form">
          <input
            type="number" placeholder="请输入手机号码" class="login-input" :maxlength="11"
            @input="e => smsLoginParam.phoneNumber = e.detail.value.trim()"
          >
          <view class="login-code">
            <input
              type="number" :maxlength="6" class="login-input" placeholder="请输入验证码"
              @input="e => smsLoginParam.code = e.detail.value.trim()"
            >
            <button class="login-button" @click="onSendSms">
              {{ buttonText }}
            </button>
          </view>

          <hope-button title="登录" @on-click="onSmsLogin" />
          <hope-button title="微信一键授权登录" @on-click="() => popupRef?.open()" />
        </view>
      </view>
    </view>
    <view>
      <hope-popup ref="popupRef" title="一键登录注册">
        <template #content>
          <form class="popup-content" @submit="onOneClickLogin">
            <!-- 获取用户头像 -->
            <view class="popup-item">
              <text class="popup-item-text">
                头像:
              </text>
              <view class="popup-item-content">
                <button class="popup-item-button" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                  <image class="popup-item-avatar" :src="oneClickLoginParams.avatarUrl" mode="scaleToFill" />

                  <input name="avatarUrl" type="text" :value="oneClickLoginParams.avatarUrl" class="hidden">
                </button>
              </view>
            </view>
            <!-- 获取用户昵称 -->
            <view class="popup-item">
              <text class="popup-item-text">
                昵称:
              </text>
              <view class="popup-item-content">
                <input name="nickname" type="nickname" placeholder="请输入您的昵称">
              </view>
            </view>

            <view class="popup-item">
              <button form-type="submit" class="m-0 w-full">
                <hope-button title="登录" class="w-full" @on-click="onOneClickLogin" />
              </button>
            </view>
            <view class="popup-item mt-2">
              <hope-button class="w-full" title="管理员测试账号一键登录" @on-click="onLoginAdmin" />
            </view>
          </form>
        </template>
      </hope-popup>
    </view>
  </view>
</template>

<style scoped lang="scss">
.login {

  &-container {
    display: flex;
    justify-content: center;
    background-color: $color-white;

    &-content {
      margin-top: 100rpx;
      width: 600rpx;
      display: flex;
      flex-direction: column;
      gap: $padding-base;
      padding: $padding-base;
    }
  }

  &-form {
    display: flex;
    flex-direction: column;
    gap: $padding-base;
  }

  &-input {
    height: 100rpx;
    padding-left: $padding-base;
    border: 1px solid $uni-border-color;
    border-radius: $border-radius-base;
    flex: 1;
  }

  &-code {
    display: flex;
    gap: $padding-base;
  }

  &-button {
    margin: 0;
    padding-inline: 40rpx;
    font-size: $font-size-sm;
    background-color: transparent;
    border: 1px solid $border-color;
    line-height: 100rpx;
    border-radius: $border-radius-base;
  }
}

.popup {
  &-item {
    display: flex;
    align-items: center;
    flex: 1;
    gap: 80rpx;
    justify-content: stretch;

    &:nth-child(2) {
      padding-block: 80rpx;
    }

    &-text {
      font-size: $font-size-base;
    }

    &-content {}

    &-button {
      width: 180rpx;
      height: 180rpx;
      border-radius: 50%;
    }

    &-avatar {
      height: 100%;
      width: 100%;
      border-radius: 50%;
    }
  }

  &-content {
    display: flex;
    gap: 80rpx;
    flex-direction: column;
  }
}
</style>
